﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace JH
{
    /// <summary>
    ///  快速搜索扩展
    /// </summary>
    public static class QuickSearchExtension
    {
        /// <summary>
        ///  从集合中模糊匹配最相似的实例
        /// </summary>
        public static T FuzzyMatch<T>(this IEnumerable<T> findRange, string query,
            Expression<Func<T, string>> processor = null)
        {
            var source = findRange.ToList();
            if (source.Count == 0) return default;

            // 将集合转换为字符串集合，用于模糊匹配，如果没有处理器，则直接调用ToString方法
            var range = source.Select(i => processor == null
                    ? i.ToString() ?? ""
                    : processor.Compile().Invoke(i))
                .ToList();

            // 创建模糊匹配器,并添加字符串,然后提交，匹配
            var matcher = SmartFuzzyMatcher.GetMatcher(query);
            matcher.AddStringsAndCommit(range);
            var result = matcher.Search(query);

            // 如果没有匹配结果，直接返回默认值
            if (result.Count <= 0) return default;

            // 从原始集合中找到匹配的实例
            var index = range.IndexOf(result[0]);
            return index >= 0 ? source[index] : default;
        }

        /// <summary>
        ///  从集合中模糊匹配最相似的实例的索引
        /// </summary>
        public static int FuzzyMatchIndex<T>(this IEnumerable<T> findRange, string query,
            Expression<Func<T, string>> processor = null)
        {
            var source = findRange.ToList();
            return source.IndexOf(source.FuzzyMatch(query, processor));
        }
    }
}